package com.kun.peng.generator.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kun.peng.generator.mapper.GenConfigMapper;
import com.kun.peng.generator.service.GenConfigService;
import com.kun.peng.generator.domain.GenConfig;
import com.kun.peng.mybatis.base.IBaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * Created on 2021/11/16.
 *
 * @author xuebaopeng
 * Description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GenConfigServiceImpl extends IBaseService<GenConfigMapper, GenConfig> implements GenConfigService {
    @Override
    public GenConfig find(String tableName) {

        GenConfig genConfig=getOne(Wrappers.lambdaQuery(GenConfig.class).eq(GenConfig::getTableName,tableName));
        if(genConfig == null){
            return new GenConfig(tableName);
        }
        return genConfig;
    }

    @Override
    public GenConfig update(String tableName, GenConfig genConfig) {
        String separator = File.separator;
        String[] paths;
        String symbol = "\\";
        if (symbol.equals(separator)) {
            paths = genConfig.getPath().split("\\\\");
        } else {
            paths = genConfig.getPath().split(File.separator);
        }
        StringBuilder api = new StringBuilder();
        for (String path : paths) {
            api.append(path);
            api.append(separator);
            if ("src".equals(path)) {
                api.append("api");
                break;
            }
        }
        genConfig.setApiPath(api.toString());
        getBaseMapper().delete(Wrappers.<GenConfig>lambdaQuery().eq(GenConfig::getTableName,tableName));
        save(genConfig);
        return genConfig;
    }
}
